package com.fushenlan.epidemicControl.service.Impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fushenlan.Vo.InhabitInfoVo;
import com.fushenlan.commons.ApiGlobalErrorDefinition;
import com.fushenlan.commons.GeneralResponse;
import com.fushenlan.enums.CommonCodeEnum;
import com.fushenlan.epidemicControl.config.JwtUtil;
import com.fushenlan.epidemicControl.dto.*;
import com.fushenlan.epidemicControl.dto.request.NucleinDetectionApplyRecordReqDTO;
import com.fushenlan.epidemicControl.mapper.InhabitantInfoMapper;
import com.fushenlan.epidemicControl.mapper.NucleinDetectionApplyRecordMapper;
import com.fushenlan.epidemicControl.mapper.NucleinDetectionApplyRecordRelationMapper;
import com.fushenlan.epidemicControl.mapper.NucleinDetectionRegisterRecordMapper;
import com.fushenlan.epidemicControl.service.InhabitantInfoService;
import com.fushenlan.epidemicControl.service.NucleinDetectionApplyRecordService;
import com.fushenlan.excel.ExportExcelUtil;
import com.fushenlan.po.NucleinDetectionApplyRecord;
import com.fushenlan.po.NucleinDetectionApplyRecordRelation;
import com.fushenlan.po.NucleinDetectionRegisterRecord;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 针对表【nuclein_detection_apply_record(核酸检测申请记录表)】的数据库操作Service实现
 * @createDate 2022-04-20 22:33:26
 */
@Service
@Slf4j
public class NucleinDetectionApplyRecordServiceImpl extends ServiceImpl<NucleinDetectionApplyRecordMapper, NucleinDetectionApplyRecord>
        implements NucleinDetectionApplyRecordService {
    /**
     * 下载核酸检测人员信息表模板信息
     */
    private static final String EXPORT_DETECTION_FILENAME = "核酸检测人员信息表模板";  //导出excel文件名
    private static final String EXPORT_DETECTION_TITLE = "核酸检测人员信息表";  //导出excel标题

    /**
     * 下载核酸检测结果详情人员列表信息
     */
    private static final String EXPORT_DETECTION_PERSON_FILENAME = "核酸检测结果详情人员列表模板";  //导出excel文件名
    private static final String EXPORT_DETECTION_PERSON_TITLE = "核酸检测结果详情人员列表";  //导出excel标题
    /**
     * 导出核酸检测结果详情人员列表excel
     */
    private static final String EXPORT_DETECTION_DATA_FILENAME = "核酸检测结果详情人员列表一览";  //导出excel文件名


    /**
     * 登录人居民表id
     */
    private static final String IN_HABITANT_ID = "inhabitantId";  //登录人居民表id

    private static final String NEIGHBORHOOD_ID = "neighborhoodId";  //登录人居委id

    @Autowired
    NucleinDetectionApplyRecordMapper nucleinDetectionApplyRecordMapper;
    @Autowired
    NucleinDetectionApplyRecordRelationMapper nucleinDetectionApplyRecordRelationMapper;
    @Autowired
    NucleinDetectionRegisterRecordMapper nucleinDetectionRegisterRecordMapper;
    @Autowired
    private InhabitantInfoMapper inhabitantInfoMapper;

    @Autowired
    private InhabitantInfoService inhabitantInfoService;

    @Override
    public List<NucleinDetectionApplyRecordRespDTO> queryNucleinDetectionApplyRecord(String startDate,
                                                                                     String endDate) {
        List<NucleinDetectionApplyRecordRespDTO> responsePage = new ArrayList<>();
        //获取当前登录人居委id
        Long neighborhoodId = Long.valueOf(JwtUtil.getUserInfo(NEIGHBORHOOD_ID)).longValue();
        log.info("当前居委id->{}", neighborhoodId);
        if (neighborhoodId == null) {
            //判断检测id是否传了
            log.info("登录已过期，请重新登录");
            return null;
        }
        try {
            responsePage = nucleinDetectionApplyRecordMapper.queryNucleinDetectionApplyRecord(startDate, endDate,neighborhoodId);

        } catch (Exception e) {
            log.error("核酸检测申请记录查询异常:" + e.getMessage());
        }
        return responsePage;
    }

    @Transactional
    @Override
    public GeneralResponse insertNucleinDetectionApplyRecord(NucleinDetectionApplyRecordReqDTO req) {
        log.info("核酸检测申请--新增检测 Request req->{}", req);
        //参数校验
        assert req != null;
        //获取当前登录人居委id
        GeneralResponse response = new GeneralResponse();
        Long tempneighborhoodId = Long.valueOf(JwtUtil.getUserInfo(NEIGHBORHOOD_ID)).longValue();
        log.info("当前居委id->{}", tempneighborhoodId);
        req.setNeighborhoodId(tempneighborhoodId);
        if (tempneighborhoodId == null) {
            //判断检测id是否传了
            return GeneralResponse.fail(ApiGlobalErrorDefinition.TOKEN_EXPIRED);
        }
        Integer detectionType = req.getDetectionType();
        Long neighborhoodId = req.getNeighborhoodId();
        List<String> ids = req.getIds();
        List<String> userids = new ArrayList<>();
        List<NucleinDetectionRegisterRecord> recordReqDtos = new ArrayList();
        try {
            NucleinDetectionApplyRecord record = new NucleinDetectionApplyRecord();
            record.setNotificationName(req.getNotificationName());
            record.setDetectionTime(req.getDetectionTime());
            record.setNoticeContent(req.getNoticeContent());
            record.setDetectionType(req.getDetectionType());
            record.setNeighborhoodId(neighborhoodId);
            if (detectionType == 1) {
                if(ids !=null){
                    ids.clear();
                }
                //全部小区 根据当前居委id 查询所有小区ids
                ids = nucleinDetectionApplyRecordMapper.queryAllResidentialIds(neighborhoodId);
                //全部小区 或 指定小区 根据当前居委id 查询所有小区ids 对应的 居民ids
                userids = nucleinDetectionApplyRecordMapper.queryAllUserIds(neighborhoodId, ids);
                if(userids != null && userids.size() > 0  ){
                    record.setDetectionNumber(userids.size());
                }else {
                    throw new Exception("根据全部小区ids"+ids+"查询数据居民信息为空，请检查");
                }
            } else if (detectionType == 2) {
                //全部小区 或 指定小区 根据当前居委id 查询所有小区ids 对应的 居民ids
                userids = nucleinDetectionApplyRecordMapper.queryAllUserIds(neighborhoodId, ids);
                if(userids != null && userids.size() > 0  ){
                    record.setDetectionNumber(userids.size());
                }else {
                    throw new Exception("根据指定小区ids"+ids+"查询数据居民信息为空，请检查");
                }

            }else if(detectionType == 3){
                if(ids != null && ids.size() > 0  ){
                    record.setDetectionNumber(ids.size());
                }else {
                    throw new Exception("指定人员的ids："+ids+"不能为空，请检查");
                }

            }
            record.setCreateUser("system");
            record.setCreateTime(new Date());
            //先查询当前数据是否存在
            QueryWrapper<NucleinDetectionApplyRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("notification_name", record.getNotificationName());
            queryWrapper.eq("detection_time", record.getDetectionTime());
            queryWrapper.eq("notice_content", record.getNoticeContent());
            queryWrapper.eq("detection_type", record.getDetectionType());
            queryWrapper.eq("neighborhood_id", neighborhoodId);
           int count =  nucleinDetectionApplyRecordMapper.selectCount(queryWrapper);
            if (count > 0){
                log.error("{},数据已存在，请不要重复插入",record.getNotificationName());
                return GeneralResponse.fail("-1", record.getNotificationName()+"数据已存在，请不要重复插入", "");
            }
            //校验
            //插入核酸申请记录
            int applyResult = nucleinDetectionApplyRecordMapper.insert(record);
            log.info("新增核酸检测申请记录表，插入条数：{}", applyResult);
            //查询刚新增核酸检测申请记录表
            QueryWrapper<NucleinDetectionApplyRecord> wrapper = new QueryWrapper<>();
            wrapper.eq("notification_name", record.getNotificationName());
            wrapper.eq("detection_time", record.getDetectionTime());
            wrapper.eq("notice_content", record.getNoticeContent());
            wrapper.eq("detection_type", record.getDetectionType());
            wrapper.eq("neighborhood_id", neighborhoodId);
            NucleinDetectionApplyRecord queryRecord = nucleinDetectionApplyRecordMapper.selectOne(wrapper);

            if (queryRecord != null) {
                if (ids != null && ids.size() > 0) {
                    List<NucleinDetectionApplyRecordRelation> relationReqDtos = new ArrayList();
                    for (String id : ids) {
                        NucleinDetectionApplyRecordRelation relationReqDTO = new NucleinDetectionApplyRecordRelation();
                        relationReqDTO.setDetectionApplyId(queryRecord.getId());
                        relationReqDTO.setDetectionType(req.getDetectionType());
                        relationReqDTO.setRelationId(id);
                        relationReqDTO.setCreateUser("system");
                        relationReqDTO.setCreateTime(new Date());
                        relationReqDtos.add(relationReqDTO);
                    }
                    log.info("核酸检测申请--新增检测申请记录快照表 Request relationReqDtos->{}", relationReqDtos);
                    //插入数据到核酸检测申请记录快照表--关联小区id 或 用户id
                    int relationRecord = nucleinDetectionApplyRecordRelationMapper.insertApplyRecordRelation(relationReqDtos);
                    log.info("新增核酸检测申请记录快照表，插入条数：{}", relationRecord);

                    //关联插入 核酸检测登记记录表
                    if (detectionType == 1 || detectionType == 2) {
                        if (userids.size() > 0) {
                            //指定检测人员
                            for (String id : userids) {
                                NucleinDetectionRegisterRecord recordReqDTO = new NucleinDetectionRegisterRecord();
                                recordReqDTO.setDetectionApplyId(queryRecord.getId());
                                recordReqDTO.setUserId(Long.parseLong(id));
                                recordReqDTO.setIfDetection(2); //'1-已检测  2-未检测',
                                recordReqDTO.setIfRegister(0); //'是否登记 1-是 0-否',
                                recordReqDTO.setCreateUser("system");
                                recordReqDTO.setCreateTime(LocalDateTime.now());
                                recordReqDtos.add(recordReqDTO);
                            }
                            log.info("核酸检测申请--新增核酸检测登记记录表 Request recordReqDtos->{}", recordReqDtos);
                            //插入数据到核酸检测申请记录快照表--关联小区id 或 用户id
                            int Record = nucleinDetectionRegisterRecordMapper.insertApplyRegisterRecord(recordReqDtos);
                            log.info("新增核酸检测登记记录表，插入条数：{}", Record);
                        } else {
                            log.info("核酸检测申请--查询所有小区ids:{} 对应的 居民ids->{}", ids, userids);
                        }
                    } else if (detectionType == 3) {
                        //指定检测人员
                        for (String id : ids) {
                            NucleinDetectionRegisterRecord recordReqDTO = new NucleinDetectionRegisterRecord();
                            recordReqDTO.setDetectionApplyId(queryRecord.getId());
                            recordReqDTO.setUserId(Long.parseLong(id));
                            recordReqDTO.setIfDetection(2); //'1-已检测  2-未检测',
                            recordReqDTO.setIfRegister(0); //'是否登记 1-是 0-否',
                            recordReqDTO.setCreateUser("system");
                            recordReqDTO.setCreateTime(LocalDateTime.now());
                            recordReqDtos.add(recordReqDTO);
                        }
                        log.info("核酸检测申请--新增核酸检测登记记录表 Request recordReqDtos->{}", recordReqDtos);
                        //插入数据到核酸检测申请记录快照表--关联小区id 或 用户id
                        int Record = nucleinDetectionRegisterRecordMapper.insertApplyRegisterRecord(recordReqDtos);
                        log.info("新增核酸检测登记记录表，插入条数：{}", Record);
                    }

                }
            }
        } catch (Exception e) {
            log.error("核酸检测申请--新增检测 报错：{}", e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return GeneralResponse.fail("-1", "核酸检测申请--新增检测 报错,"+e.getMessage(), "");
        }
        return GeneralResponse.success();
    }

    @Override
    public GeneralResponse<NucleinDetectionApplyRecordRespDTO> LookNucleinDetectionApplyRecord( Long detectionId) {
        GeneralResponse<NucleinDetectionApplyRecordRespDTO> response = new GeneralResponse<>();
        NucleinDetectionApplyRecordRespDTO detectionApplyRecordRespDTO = new NucleinDetectionApplyRecordRespDTO();
        try {
            QueryWrapper<NucleinDetectionApplyRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id",  detectionId);
            NucleinDetectionApplyRecord record = nucleinDetectionApplyRecordMapper.selectOne(queryWrapper);
            if (record != null) {
                Integer detectionType = record.getDetectionType();
                Long detectionApplyId = record.getId();
                QueryWrapper<NucleinDetectionApplyRecordRelation> wrapper = new QueryWrapper<>();
                wrapper.eq("detection_apply_id", detectionApplyId);
                wrapper.eq("detection_type", detectionType);
                List<NucleinDetectionApplyRecordRelation> relationsList = nucleinDetectionApplyRecordRelationMapper.selectList(wrapper);
                if (detectionType == 1 || detectionType == 2) {
                    //获取小区信息列表
                    List<CommunityinfoRespDTO> communityList = nucleinDetectionApplyRecordMapper.queryCommunityList(relationsList);
                    detectionApplyRecordRespDTO.setCommunityList(communityList);
                } else if (detectionType == 3) {
                    //获取居民信息列表
                    List<InhabitInfoVo> inhabitInfoVos = nucleinDetectionApplyRecordMapper.findInhabitList(relationsList);
                    detectionApplyRecordRespDTO.setInhabitInfoVos(inhabitInfoVos);

                }
                detectionApplyRecordRespDTO.setId(record.getId());
                detectionApplyRecordRespDTO.setDetectionTime(record.getDetectionTime());
                detectionApplyRecordRespDTO.setNeighborhoodId(record.getNeighborhoodId());
                detectionApplyRecordRespDTO.setNotificationName(record.getNotificationName());
                detectionApplyRecordRespDTO.setNoticeContent(record.getNoticeContent());
                detectionApplyRecordRespDTO.setDetectionType(record.getDetectionType());
                response.setData(detectionApplyRecordRespDTO);
            }

        } catch (Exception e) {
            log.error("查看核酸检测记录信息查询数据库异常：{}", e.getMessage());
            return GeneralResponse.fail("-1", "查看核酸检测记录信息查询数据库异常", "");
        }
        return response;
    }


    @Override
    public void downloadNucleinDetectionApplyRecordModel(List<?> list, HttpServletResponse response) {
        // 导出数据，数据，数据类型，文件名称，表名，响应对象
        ExportExcelUtil.exportExcel(list, DetectionPersonalInfoRespDTO.class, EXPORT_DETECTION_FILENAME, EXPORT_DETECTION_TITLE, response);
    }

    @Override
    public void downloadNucleinDetectionResultDetails(List<?> list, HttpServletResponse response) {
        // 导出数据，数据，数据类型，文件名称，表名，响应对象
        ExportExcelUtil.exportExcel(list, DetectionPersonalInfoDetailsRespDTO.class, EXPORT_DETECTION_PERSON_FILENAME, EXPORT_DETECTION_PERSON_TITLE, response);
    }

    /**
     * 上传核酸检测申请记录列表，根据三要素查询居民相关信息 ，并返回
     *
     * @param
     * @param multipartFile
     * @param response
     * @return
     */
    @Override
    public GeneralResponse<List<DetectionPersonalInfoRespDTO>> uploadNucleinDetectionApplyRecordList(MultipartFile multipartFile, HttpServletResponse response) throws Exception {
        GeneralResponse<List<DetectionPersonalInfoRespDTO>> response1 = new GeneralResponse<>();
        List<DetectionPersonalInfoRespDTO> resp = new ArrayList<>();
        //获取当前登录人居委id
        Long neighborhoodId = Long.valueOf(JwtUtil.getUserInfo(NEIGHBORHOOD_ID)).longValue();
        if (neighborhoodId == null) {
            //判断检测id是否传了
            return GeneralResponse.fail(ApiGlobalErrorDefinition.TOKEN_EXPIRED);
        }
        //暂时模拟读取本地文件test
        //FileInputStream inputStream = new FileInputStream(new File("C:\\Users\\PC\\Downloads\\核酸检测人员信息表模板-20220430.xls"));
//        FileInputStream inputStream = new FileInputStream(new File(multipartFile));
//        MultipartFile  file;
        byte[] byteArr = multipartFile.getBytes();
        InputStream inputStream = new ByteArrayInputStream(byteArr);
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        //解析导入列表
        List<DetectionPersonalInfoRespDTO> respDTOS = ExcelImportUtil.importExcel(inputStream,
                DetectionPersonalInfoRespDTO.class, params);
        log.info("解析导入文件：{}",respDTOS);
        //根据三要素查询居民信息
        int count = 0; //初始化导入成功数量
        for (DetectionPersonalInfoRespDTO tmp : respDTOS) {
            DetectionPersonalInfoRespDTO dto = new DetectionPersonalInfoRespDTO();
            InhabitantInfoDto inhabitantInfoDto = new InhabitantInfoDto();
            inhabitantInfoDto.setNeighborhoodId(neighborhoodId.intValue());
            inhabitantInfoDto.setUserName(tmp.getUserName());
            inhabitantInfoDto.setIdentifyType(tmp.getIdentifyType());
            inhabitantInfoDto.setIdentifyNo(tmp.getIdentifyNo());

//            List<InhabitInfoVo> list = inhabitantInfoMapper.queryInhabitList(inhabitantInfoDto);
            List<InhabitInfoVo> list = inhabitantInfoService.findInhabitList(inhabitantInfoDto);
            if (list != null && list.size() != 0) {
                if (list.size() > 1) {
                    throw new Exception("查询结果异常");
                }
                count++;
                dto.setId(list.get(0).getId().longValue());
                dto.setAddress(list.get(0).getAddress());
                dto.setUserName(list.get(0).getUserName());
                dto.setPhoneNumber(list.get(0).getPhoneNumber());
                dto.setIdentifyType(list.get(0).getIdentifyType());
                dto.setIdentifyNo(list.get(0).getIdentifyNo());

                resp.add(dto);
            }
        }
        resp.stream().distinct().collect(Collectors.toList());
        log.info("文件上传查询结果：{}",resp);
        response1.setData(resp);
        log.info("上传核酸检测人员信息excel列表成功，excel总数为{}条，成功{}条", respDTOS.size(), count);
        return response1;
    }

    /**
     * 上传核酸检测结果详情人员，根据三要素查询居民相关信息 ，并修改 是否已检测为 ：是 并返回
     *
     * @param
     * @param multipartFile
     * @param response
     * @return
     */
    @Transactional
    @Override
    public GeneralResponse<List<DetectionPersonalInfoRespDTO>> uploadNucleinDetectionResultDetails(MultipartFile multipartFile,Long detectionId, HttpServletResponse response) throws Exception {
        //获取当前登录人居委id
        Long neighborhoodId = Long.valueOf(JwtUtil.getUserInfo(NEIGHBORHOOD_ID)).longValue();
        if (neighborhoodId == null) {
            //判断检测id是否传了
            return GeneralResponse.fail(ApiGlobalErrorDefinition.TOKEN_EXPIRED);
        }
        GeneralResponse<List<DetectionPersonalInfoRespDTO>> generalResponse = new GeneralResponse<>();
        List<DetectionPersonalInfoRespDTO> newRespDTOs = new ArrayList<>();
        List<DetectionPersonalInfoRespDTO> respDTOS = new ArrayList<>();
//        byte[] byteArr = multipartFile.getBytes();
//        InputStream inputStream = new ByteArrayInputStream(byteArr);
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        //解析导入人员列表
        List<DetectionPersonalInfoRespDTO> respDetailsDTOS = ExcelImportUtil.importExcel(multipartFile.getInputStream(),
                DetectionPersonalInfoRespDTO.class, params);
        //根据三要素查询居民信息
        int count = 0; //初始化导入成功数量
        int updateCount = 0; //修改成功数量
        for (DetectionPersonalInfoRespDTO tmp : respDetailsDTOS) {
            DetectionPersonalInfoRespDTO dto = new DetectionPersonalInfoRespDTO();
            InhabitantInfoDto inhabitantInfoDto = new InhabitantInfoDto();
            inhabitantInfoDto.setNeighborhoodId(neighborhoodId.intValue());
            inhabitantInfoDto.setUserName(tmp.getUserName());
            inhabitantInfoDto.setIdentifyType(tmp.getIdentifyType());
            inhabitantInfoDto.setIdentifyNo(tmp.getIdentifyNo());

//            List<InhabitInfoVo> list = inhabitantInfoMapper.queryInhabitList(inhabitantInfoDto);
            List<InhabitInfoVo> list = inhabitantInfoService.findInhabitList(inhabitantInfoDto);
            if (list != null && list.size() != 0) {
                if (list.size() > 1) {
                    throw new Exception("查询结果异常");
                }
                count++;
                dto.setId(list.get(0).getId().longValue());
                dto.setAddress(list.get(0).getAddress());
                dto.setUserName(list.get(0).getUserName());
                dto.setPhoneNumber(list.get(0).getPhoneNumber());
                dto.setIdentifyType(list.get(0).getIdentifyType());
                dto.setIdentifyNo(list.get(0).getIdentifyNo());
                dto.setIfDetection(tmp.getIfDetection());
                respDTOS.add(dto);
            }
        }
            log.info("匹配导入的数据：{}，导入成功：{}", respDTOS,count);
            if (respDTOS.size() > 0) {
                for (DetectionPersonalInfoRespDTO record : respDTOS) {
                    NucleinDetectionRegisterRecord temp = new NucleinDetectionRegisterRecord();
                    temp.setIfDetection(record.getIfDetection());
                    temp.setUpdateUser("system");
                    temp.setUpdateTime(LocalDateTime.now());
                    //条件 userId and 检测id
                    QueryWrapper<NucleinDetectionRegisterRecord> queryWrapper = new QueryWrapper();
                    queryWrapper.eq("user_id", record.getId());
                    queryWrapper.eq("detection_apply_id", detectionId);
                    int result = nucleinDetectionRegisterRecordMapper.update(temp, queryWrapper);
                    if(result > 0 ){
                        updateCount++;
                    }

                }
            }
        //delete
//        if (respDetailsDTOS != null && respDetailsDTOS.size() > 0) {
//            for (DetectionPersonalInfoDetailsRespDTO record : respDetailsDTOS) {
//                DetectionPersonalInfoRespDTO temp = new DetectionPersonalInfoRespDTO();
//                temp.setAddress(record.getAddress());
//                temp.setUserName(record.getUserName());
//                temp.setIdentifyType(record.getIdentifyType());
//                temp.setIdentifyNo(record.getIdentifyNo());
//                temp.setIfDetection(record.getIfDetection());
//                respDTOS.add(temp);
//            }
//        } else {
//            log.warn("解析导入人员列表数据为空");
//            return GeneralResponse.fail("-1", "解析导入人员列表数据为空", "");
//        }
//
//        //获取当前查询人员信息 修改为 查询当前居民信息
//        IPage<DetectionPersonalInfoRespDTO> personalInfoRespDTOPage = nucleinDetectionApplyRecordMapper.queryNucleinDetectionResultDetails(new Page<>(1, -1), neighborhoodId, 1L, "222", 3, 1, 1, detectionId);
//        List<DetectionPersonalInfoRespDTO> personalInfoRespDTOList = personalInfoRespDTOPage.getRecords();
//        int count = 0;
        //根据用户ids 过滤出数据
//        if (respDTOS.size() > 0) {
//            newRespDTOs = respDTOS.stream()
//                    .map(
//                            user -> personalInfoRespDTOList.stream()
//                                    .filter(log -> user.getUserName().equals(log.getUserName()))
//                                    .filter(log -> user.getIdentifyType().equals(log.getIdentifyType()))
//                                    .filter(log -> user.getIdentifyNo().equals(log.getIdentifyNo()))
//                                    .findAny()
//                                    .orElse(null)
//                    ).collect(Collectors.toList());
//            newRespDTOs.removeAll(Collections.singleton(null));
//            log.info("匹配导入的数据：{}", newRespDTOs);
//            if (newRespDTOs.size() > 0) {
//                for (DetectionPersonalInfoRespDTO record : newRespDTOs) {
//                    NucleinDetectionRegisterRecord temp = new NucleinDetectionRegisterRecord();
//                    temp.setIfDetection(record.getIfDetection());
//                    temp.setUpdateUser("system");
//                    temp.setUpdateTime(LocalDateTime.now());
//                    //条件 userId and 检测id
//                    QueryWrapper<NucleinDetectionRegisterRecord> queryWrapper = new QueryWrapper();
//                    queryWrapper.eq("user_id", record.getId());
//                    queryWrapper.eq("detection_apply_id", detectionId);
//                    count = nucleinDetectionRegisterRecordMapper.update(temp, queryWrapper);
//                    count++;
//                }
//            }
//
//        }

        log.info("获取当前查询人员信息 Response queryNucleinDetectionResultDetails->{}", respDTOS);
        generalResponse.setData(respDTOS);
        log.info("上传核酸检测结果详情人员excel列表成功，excel总数为{}条，成功{}条", respDetailsDTOS.size(), count);
        return generalResponse;
    }

    /**
     * 核酸检测结果查询
     *
     * @param startDate,endDate
     * @return
     */
    @Override
    public List<NucleinDetectionResultRespDTO> queryNucleinDetectionResult(String startDate,
                                                                           String endDate,
                                                                           Integer pageSize,
                                                                           Integer pageNo) {
        List<NucleinDetectionResultRespDTO> response = new ArrayList<>();
        //获取当前登录人居委id
        Long neighborhoodId = Long.valueOf(JwtUtil.getUserInfo(NEIGHBORHOOD_ID)).longValue();
        log.info("当前居委id->{}", neighborhoodId);
        if (neighborhoodId == null) {
            //判断检测id是否传了
            log.info("登录已过期，请重新登录");
            return null;
        }
        try {
            //sql查询
//            nucleinDetectionApplyRecordMapper.queryNucleinDetectionResult(new Page<>(pageNo, pageSize),startDate,endDate,neighborhoodId);

            List<NucleinDetectionApplyRecordRespDTO> detectionApplyRecords = nucleinDetectionApplyRecordMapper.queryNucleinDetectionApplyRecord(startDate, endDate,neighborhoodId);
            if (detectionApplyRecords != null) {
                for (NucleinDetectionApplyRecordRespDTO record : detectionApplyRecords) {
                    NucleinDetectionResultRespDTO nucleinDetectionResultRespDTO = new NucleinDetectionResultRespDTO();
                    nucleinDetectionResultRespDTO.setId(record.getId());
                    nucleinDetectionResultRespDTO.setDetectionTime(record.getDetectionTime());
                    nucleinDetectionResultRespDTO.setNotificationName(record.getNotificationName());
                    nucleinDetectionResultRespDTO.setNoticeContent(record.getNoticeContent());
                    nucleinDetectionResultRespDTO.setDetectionType(record.getDetectionType());
                    nucleinDetectionResultRespDTO.setDetectionNumber(record.getDetectionNumber());
                    //获取未检测人数
                    Long id = record.getId();
                    String ifDetection = "2";
                    int noDetectionNum = nucleinDetectionApplyRecordMapper.getTargetNum(id, ifDetection, "", "",  neighborhoodId);
                    nucleinDetectionResultRespDTO.setNoDetectionNum(noDetectionNum);
                    //未登记人数
                    String ifRegister = "0";
                    int noRegisterNum = nucleinDetectionApplyRecordMapper.getTargetNum(id, "", ifRegister, "",neighborhoodId);
                    nucleinDetectionResultRespDTO.setNoRegisterNum(noRegisterNum);
                    //阳性人数
                    String detectionResult = "1";
                    int sunNum = nucleinDetectionApplyRecordMapper.getTargetNum(id, "", "", detectionResult,neighborhoodId);
                    nucleinDetectionResultRespDTO.setSunNum(sunNum);
                    //未转运人数
                    String userStatus = "1";
                    int noTransportNum = nucleinDetectionApplyRecordMapper.getNoTransportNum(id, userStatus,neighborhoodId);
                    nucleinDetectionResultRespDTO.setNoTransportNum(noTransportNum);
                    response.add(nucleinDetectionResultRespDTO);
                }
            }

        } catch (Exception e) {
            log.error("核酸检测结果查询数据库异常：{}", e.getMessage());
        }
        return response;
    }

    /**
     * 通知登记
     *
     * @param detectionId
     * @return
     */
    @Override
    public int noticeRegister(Long detectionId) {
        //先查询当前申请detectionId 如果用户之前已经发布过通知登记，点击时提示“已发布通知登记，
        // 请确认是否再次通知”，确认后再发一次给未登记的人员
        try {
            QueryWrapper<NucleinDetectionApplyRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", detectionId);
            queryWrapper.eq("if_input_results", 1);
            Integer record = nucleinDetectionApplyRecordMapper.selectCount(queryWrapper);
            //修改
            NucleinDetectionApplyRecord detectionApplyRecord = new NucleinDetectionApplyRecord();
            //'是否开始录入结果 0-否 1-是 '
            detectionApplyRecord.setId(detectionId);
            detectionApplyRecord.setIfInputResults(1);
            Integer updateRecord = nucleinDetectionApplyRecordMapper.updateById(detectionApplyRecord);
            log.info("通知登记，修改申请记录表，影响行数：{} ", updateRecord);
            return updateRecord;
        } catch (Exception e) {
            log.error("通知登记异常：{}", e.getMessage());
        }
        return 0;
    }

    @Override
    public GeneralResponse<IPage<DetectionPersonalInfoRespDTO>> queryNucleinDetectionResultDetails(Long community,
                                                                                                   String name,
                                                                                                   Integer detectionResult,
                                                                                                   Integer userStatus,
                                                                                                   Integer ifDetection,
                                                                                                   Long detectionId,
                                                                                                   Integer pageSize,
                                                                                                   Integer pageNo) {
        GeneralResponse<IPage<DetectionPersonalInfoRespDTO>> response = new GeneralResponse<>();
        //获取当前登录人居委id
        Long neighborhoodId = Long.valueOf(JwtUtil.getUserInfo(NEIGHBORHOOD_ID)).longValue();
        log.info("当前居委id->{}", neighborhoodId);
        if (neighborhoodId == null) {
            //判断检测id是否传了
            log.info("登录已过期，请重新登录");
            return GeneralResponse.fail(ApiGlobalErrorDefinition.TOKEN_EXPIRED);
        }
        try {
            //获取当前登录人
            IPage<DetectionPersonalInfoRespDTO> respDTO = nucleinDetectionApplyRecordMapper.queryNucleinDetectionResultDetails(new Page<>(pageNo, pageSize), neighborhoodId, community, name, detectionResult, userStatus, ifDetection, detectionId);

//            //查询阳性人员信息，拼接转运状态信息
//            List<DetectionPersonalStatusInfoDo> statusInfoDos = nucleinDetectionApplyRecordMapper.queryNucleinDetectionResultStatusDetails(detectionId,userStatus);
//
            response.setData(respDTO);
        } catch (Exception e) {
            log.error("核酸检测结果查询数据库异常：{}", e.getMessage());
            return GeneralResponse.fail("-1", "核酸检测结果查询数据库异常", "");
        }
        return response;
    }

    /**
     * 导出检测结果详情人员信息
     * @param community
     * @param name
     * @param detectionResult
     * @param userStatus
     * @param ifDetection
     * @param detectionId
     * @param response
     * @return
     */
    @Override
    public GeneralResponse exportNucleinDetectionResultDetails(
                                                               Long community,
                                                               String name,
                                                               Integer detectionResult,
                                                               Integer userStatus,
                                                               Integer ifDetection,
                                                               Long detectionId,
                                                               HttpServletResponse response) {

        //获取当前登录人居委id
        Long neighborhoodId = Long.valueOf(JwtUtil.getUserInfo(NEIGHBORHOOD_ID)).longValue();
        log.info("当前居委id->{}", neighborhoodId);
        if (neighborhoodId == null) {
            //判断检测id是否传了
            log.info("登录已过期，请重新登录");
            return GeneralResponse.fail(ApiGlobalErrorDefinition.TOKEN_EXPIRED);
        }
        IPage<DetectionPersonalInfoRespDTO> personalInfoRespDTOPage = nucleinDetectionApplyRecordMapper.queryNucleinDetectionResultDetails(new Page<>(1, -1), neighborhoodId, community, name, detectionResult, userStatus, ifDetection, detectionId);
        List<DetectionPersonalInfoRespDTO> personalInfoRespDTOList = personalInfoRespDTOPage.getRecords();
        //根据用户ids 过滤出数据
//        personalInfoRespDTOList.stream().filter((DetectionPersonalInfoRespDTO s) -> userIds.contains(s.getId()))
//                .collect(Collectors.toList());
        log.info("导出人员信息 Response exportNucleinDetectionResultDetails->{}", personalInfoRespDTOList);
        ExportExcelUtil.exportExcel(personalInfoRespDTOList, DetectionPersonalInfoRespDTO.class, EXPORT_DETECTION_DATA_FILENAME, EXPORT_DETECTION_PERSON_TITLE, response);
        return null;
    }

    /**
     * 密接查询
     *
     * @param id 用户id
     * @return
     */
    @Override
    public GeneralResponse<List<DetectionPersonalInfoRespDTO>> querycloseContactInfo(Long id, Long detectionId) {
        log.info("密接查询 Request userId->{},detectionId->{}", id, detectionId);
        List<DetectionPersonalInfoRespDTO> personalInfoRespDTOS = nucleinDetectionApplyRecordMapper.querycloseContactInfo(id, detectionId);
        log.info("密接查询 Response personalInfoRespDTOS->{}", personalInfoRespDTOS);
        return GeneralResponse.success(personalInfoRespDTOS);
    }

    /**
     * 修改检测结果
     *
     * @param id 用户id
     * @return
     */
    @Transactional
    @Override
    public int updateDetectionResult(Long id, Long detectionId, Integer detectionResult) {
        log.info("修改检测结果 Request userId->{},detectionId->{}", id, detectionId);
        NucleinDetectionRegisterRecord detectionRegisterRecord = new NucleinDetectionRegisterRecord();
        detectionRegisterRecord.setDetectionResult(detectionResult);
        detectionRegisterRecord.setUpdateTime(LocalDateTime.now());
        detectionRegisterRecord.setUpdateUser("system");
        QueryWrapper<NucleinDetectionRegisterRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", id);
        queryWrapper.eq("detection_apply_id", detectionId);
        int result = nucleinDetectionRegisterRecordMapper.update(detectionRegisterRecord, queryWrapper);
        log.info("修改检测结果 Response personalInfoRespDTOS->{}", result);
        return result;
    }
}
